package com.tianji.promotion.service.impl;

import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.autoconfigure.redisson.annotations.Lock;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.promotion.constans.PromotionConstants;
import com.tianji.promotion.domain.dto.UserCouponDTO;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.po.UserCoupon;
import com.tianji.promotion.domain.query.UserCouponQuery;
import com.tianji.promotion.domain.vo.CouponVO;
import com.tianji.promotion.enums.ExchangeCodeStatus;
import com.tianji.promotion.enums.UserCouponStatus;
import com.tianji.promotion.mapper.CouponMapper;
import com.tianji.promotion.mapper.UserCouponMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.tianji.promotion.service.IUserCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.strategy.discount.DiscountStrategy;
import com.tianji.promotion.utils.CodeUtil;
import com.tianji.promotion.utils.MyLock;
import com.tianji.promotion.utils.RedisLock;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户领取优惠券的记录，是真正使用的优惠券信息 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2025-03-23
 */
@Service
@RequiredArgsConstructor
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements IUserCouponService {

    private final CouponMapper couponMapper;
    private final IExchangeCodeService codeService;
    private final StringRedisTemplate redisTemplate;
    private final RabbitMqHelper mqHelper;

    @Override
    @Transactional
    public void exchangeCoupon(String code) {
        //1.检验并解析兑换码
        long serialNum = CodeUtil.parseCode(code);
        //2.校验是否已经兑换过 SETBIT KEY 4 1
        boolean exchanged = codeService.updateExchangeMark(serialNum, true);
        if (exchanged) {
            throw new BizIllegalException("兑换码已经兑换过!");
        }
        try {
            //3.查询兑换码
            Long couponId = codeService.exchangeTargetId(serialNum);
            if (couponId == null) {
                throw new BizIllegalException("兑换码不存在!");
            }
            Coupon coupon = queryCouponByCache(couponId);
            //4.是否过期
            LocalDateTime now = LocalDateTime.now();
            if (now.isAfter(coupon.getIssueEndTime()) || now.isBefore(coupon.getIssueBeginTime())) {
                throw new BizIllegalException("优惠券活动未开始或已经结束!");
            }
//            //5.校验并创建优惠券
//            //5.1查询优惠券
//            Coupon coupon = couponMapper.selectById(exchangeCode.getExchangeTargetId());
//            //5.2获取用户
//            Long userId = UserContext.getUser();
////            checkAndCreateUserCoupon(userId, coupon);
//
//            //8.更新兑换吗的状态
//            codeService.lambdaUpdate()
//                    .set(ExchangeCode::getUserId, userId)
//                    .set(ExchangeCode::getStatus, ExchangeCodeStatus.USED)
//                    .eq(ExchangeCode::getId, serialNum)
//                    .update();
//        } catch (Exception e) {
//            //重置兑换码标记为 0
//            codeService.updateExchangeMark(serialNum, false);
//            throw e;
//        }
            //5.校验每人限领数量
            Long userId = UserContext.getUser();
            //5.1查询领取数量
            String key = PromotionConstants.USER_COUPON_CACHE_KEY_PREFIX + couponId;
            Long count = redisTemplate.opsForHash().increment(key,userId.toString(),1);
            //5.2校验限领数量
            if (count > coupon.getUserLimit()) {
                throw new BizIllegalException("您已经超出限制优惠券了!");
            }

            //6.发送MQ消息通知
            UserCouponDTO uc = new UserCouponDTO();
            uc.setCouponId(couponId);
            uc.setUserId(userId);
            uc.setSerialNum((int) serialNum);
            mqHelper.send(MqConstants.Exchange.PROMOTION_EXCHANGE,MqConstants.Key.COUPON_RECEIVE,uc);
        }catch (Exception e){
            //重置兑换码标记为 0
            codeService.updateExchangeMark(serialNum, false);
            throw e;
        }
    }

    @Override
    @Lock(name = "lock:ccoupon:#{couponId}")
    public void receiveCoupon(Long couponId) {
        //1.查询优惠券
        Coupon coupon = queryCouponByCache(couponId);
        if (coupon == null) {
            throw new BadRequestException("优惠券不存在!");
        }
        //2.校验发放时间
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(coupon.getIssueBeginTime()) || now.isAfter(coupon.getIssueEndTime())) {
            throw new BadRequestException("优惠券不在发放时间范围内!");
        }
        //3.校验库存
        if (coupon.getTotalNum() <= 0) {
            throw new BadRequestException("优惠券已发放完!");
        }
        Long userId = UserContext.getUser();
        //4.校验并创建优惠券
        //4.1查询领取数量
        String key = PromotionConstants.USER_COUPON_CACHE_KEY_PREFIX + couponId;
        Long count = redisTemplate.opsForHash().increment(key, userId.toString(), 1);
        //4.2校验仙林数量
        if (count > coupon.getUserLimit()) {
            throw new BadRequestException("您已经超出限制优惠券了!");
        }
        //5.扣减优惠券库存
        redisTemplate.opsForHash().increment(
                PromotionConstants.COUPON_CACHE_KEY_PREFIX, "totalNum", -1);
        //6.发送MQ消息
        UserCouponDTO userCouponDTO = new UserCouponDTO();
        userCouponDTO.setCouponId(couponId);
        userCouponDTO.setUserId(userId);
        mqHelper.send(
                MqConstants.Exchange.PROMOTION_EXCHANGE,
                MqConstants.Key.COUPON_RECEIVE,
                userCouponDTO);
        //4.1创建锁对象
//        RLock lock = redissonClient.getLock(key);
//        //4.2尝试获取锁
//        boolean isLock = lock.tryLock();
//        //4.3判断锁是否获取成功
//        if (!isLock) {
//            throw new BizIllegalException("请勿频繁领取优惠券!");
//        }
//        try {
//            //4.4成功获取，执行业务
//            IUserCouponService userCouponService = (IUserCouponService) AopContext.currentProxy();
//            userCouponService.checkAndCreateUserCoupon(userId, coupon);
//        }finally {
//            //释放锁
//            lock.unlock();
//        }
//        IUserCouponService userCouponService = (IUserCouponService) AopContext.currentProxy();
//        userCouponService.checkAndCreateUserCoupon(userId, coupon);

    }

    private Coupon queryCouponByCache(Long couponId) {
        //1.准备 KEy
        String key = PromotionConstants.COUPON_CACHE_KEY_PREFIX + couponId;
        //2.查询
        Map<Object, Object> objMap = redisTemplate.opsForHash().entries(key);
        if (objMap.isEmpty()) {
            return null;
        }
        //3.数据反序列化
        return BeanUtils.mapToBean(objMap, Coupon.class, false, CopyOptions.create());
    }


    @Transactional
    @Override
    public void checkAndCreateUserCoupon(UserCouponDTO uc) {
        //1.查询优惠券
        Coupon coupon = couponMapper.selectById(uc.getCouponId());
       if (coupon == null){
           throw new BizIllegalException("优惠券不存在!");
       }
        //2.更新优惠券已发放的数量
        int r = couponMapper.incrIssueNum(coupon.getId());
        if (r == 0) {
            throw new BizIllegalException("优惠券库存不足!");
        }
        //3.新增一个优惠券
        saveUserCoupon(uc.getUserId(), coupon);
    }

    private void saveUserCoupon(Long userId, Coupon coupon) {
        //1.基本信息
        UserCoupon uc = new UserCoupon();
        uc.setCouponId(coupon.getId());
        uc.setUserId(userId);
        //2.生成有效期信息
        LocalDateTime termBeginTime = coupon.getTermBeginTime();
        LocalDateTime termEndTime = coupon.getTermEndTime();
        if (termBeginTime == null) {
            termBeginTime = LocalDateTime.now();
            termEndTime = termBeginTime.plusDays(coupon.getTermDays());
        }
        uc.setTermBeginTime(termBeginTime);
        uc.setTermEndTime(termEndTime);
        //3.保存
        save(uc);
    }

    @Override
    public PageDTO<CouponVO> queryMyCouponPage(UserCouponQuery query) {
        //1.获取当前用户登录
        Long userId = UserContext.getUser();
        //2.分页查询优惠券
        Page<UserCoupon> page = lambdaQuery()
                .eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getStatus, query.getStatus())
                .page(query.toMpPage(new OrderItem("term_end_time", true)));
        List<UserCoupon> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        //3.获取优惠券详细信息
        //3.1获取用户券关联的优惠券id
        Set<Long> couponIds = records.stream().map(UserCoupon::getCouponId).collect(Collectors.toSet());
        //3.2查询
        List<Coupon> coupons = couponMapper.selectBatchIds(couponIds);

        //4.封装vo
        return PageDTO.of(page, BeanUtils.copyList(coupons, CouponVO.class));
    }

    @Override
    @Transactional
    public void writeoffCoupon(List<Long> userCouponIds) {
        //1.查询优惠券
        List<UserCoupon> userCoupons = listByIds(userCouponIds);
        if (CollUtils.isEmpty(userCoupons)){
            return;
        }
        //2.处理数据
        List<UserCoupon> list = userCoupons.stream()
                //过滤无关券
                .filter(coupon -> {
                    if (coupon == null){
                        return false;
                    }
                    if (UserCouponStatus.UNUSED != coupon.getStatus()){
                        return false;
                    }
                    LocalDateTime now = LocalDateTime.now();
                    return !now.isBefore(coupon.getTermBeginTime()) && !now.isAfter(coupon.getTermEndTime());
                })
                //组织新增数据
                .map(coupon -> {
                    UserCoupon c = new UserCoupon();
                    c.setId(coupon.getId());
                    c.setStatus(UserCouponStatus.USED);
                    return c;
                })
                .collect(Collectors.toList());
        //4.核销，修改优惠券状态
        boolean success = updateBatchById(list);
        if (!success){
            return;
        }
        // 5.更新已使用数量
        List<Long> couponIds = userCoupons.stream().map(UserCoupon::getCouponId).collect(Collectors.toList());
        int c = couponMapper.incrUsedNum(couponIds, 1);
        if (c < 1) {
            throw new DbException("更新优惠券使用数量失败！");
        }
    }

    @Override
    @Transactional
    public void refundCoupon(List<Long> userCouponIds) {
        //1。查询优惠券
        List<UserCoupon> userCouponss = listByIds(userCouponIds);
        if (CollUtils.isEmpty(userCouponss)){
            return;
        }
        //2.处理优惠券数据
        List<UserCoupon> list =  userCouponss.stream()
                //过滤无效券
                .filter(coupon -> coupon != null && UserCouponStatus.USED == coupon.getStatus())
                //跟新状态字段
                .map(Coupon ->{
                    UserCoupon coupon = new UserCoupon();
                    coupon.setId(Coupon.getId());
                    //3.判断有效期
                    LocalDateTime now = LocalDateTime.now();
                    UserCouponStatus status = now.isAfter(Coupon.getTermEndTime())?
                            UserCouponStatus.EXPIRED:UserCouponStatus.UNUSED;
                    coupon.setStatus(status);
                    return coupon;
                }).collect(Collectors.toList());
        //4.修改优惠券状态
        boolean success = updateBatchById(list);
        if (!success){
            return;
        }
        //5.更新已使用数量
        List<Long> couponIds = userCouponss.stream().map(UserCoupon::getCouponId).collect(Collectors.toList());
        int c = couponMapper.incrUsedNum(couponIds, -1);
        if (c < 1) {
            throw new DbException("更新优惠券使用数量失败！");
        }
    }

    @Override
    public List<String> queryDiscountRules(List<Long> userCouponIds) {
        //1.查询我得优惠券信息
        List<Coupon> userCoupons = baseMapper.queryCouponByUserCouponIds(userCouponIds, UserCouponStatus.UNUSED);
        if (CollUtils.isEmpty(userCoupons)){
            return Collections.emptyList();
        }
        //2.转换规则
        return userCoupons.stream()
                .map(c -> DiscountStrategy.getDiscount(c.getDiscountType()).getRule(c))
                .collect(Collectors.toList());
    }
}
